from flask import Flask, request, jsonify
import requests

app = Flask(__name__)

# 缓存 access_token
access_token = None

# 回调接口，接收授权码
@app.route('/callback2')
def callback2():
    global access_token
    code = request.args.get('code')
    # 调用统一认证服务获取令牌
    token_url = 'http://192.168.6.128:5000/token'
    data = {
        "code": code
    }
    response = requests.post(token_url, data=data)
    if response.status_code == 200:
        access_token = response.json().get('access_token')
        # 调用统一认证服务获取用户信息
        userinfo_url = 'http://192.168.6.128:5000/userinfo'
        headers = {
            "Authorization": f"Bearer {access_token}"
        }
        userinfo_response = requests.get(userinfo_url, headers=headers)
        if userinfo_response.status_code == 200:
            user_info = userinfo_response.json()
            return jsonify({
                "message": "Login successful to Sub - Function 2",
                "user_info": user_info
            })
    return jsonify({"error": "Failed to get access token or user info"}), 400

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True, port=5002)